import React, { Component, PureComponent } from 'react'
import "./index.css"

export default class Parent extends PureComponent {
  state = {carName: "捷途履行者", name:"小星"}

  changeCar=() => {
    // this.setState({carName: "宝马525"})  // 父组件子组件都会更新，重新渲染
    //this.setState({})  // 这里没有对state做出更新，不应该重新渲染，
    // this.setState({carName: "宝马325"})
    /** 这样修改state是不会触发组件的重新render的， 浅拷贝
    const newObj = this.state
    newObj.carName = "宝马325"
    this.setState(newObj)
    console.log("++++", this.state.carName)
     */

    // 深拷贝， 会触发组件的重新render
    const newObj = {...this.state, carName: "宝马325"}
    this.setState(newObj)
  }

  changeName=() => {
    this.setState({name: "小何"})
  }
  

  // shouldComponentUpdate(nextProps, nextState){
  //   console.log(this.state.carName)
  //   console.log(nextProps, nextState)
  //   if(this.state.carName !== nextState.carName) return true
  //   return false
  // }
  

  render() {
    console.log("parent")
    return (
      <div className='parent'>
        <h3>我是父组件， 我有辆车:{this.state.carName}</h3>
        <p>我儿子的名字是：{this.state.name}</p>
        <button onClick={this.changeCar}>换车</button>
        <button onClick={this.changeName}>换名字</button>
        <Child name={this.state.name}/>
      </div>
    )
  }
}


class Child extends PureComponent {

  // shouldComponentUpdate(nextProps, nextState){
  //   if(nextProps.name === this.props.name) return false
  //   return true 
  // }

  render() {
    console.log("child", this.props.name)
    return (
      <div className='child'>
        <h3>我是子组件</h3>
          {/* <p>老父亲给我的车{this.props.carName}</p> */}
        <p>我名字：{this.props.name}</p>
      </div>
    )
  }
}
